#include "messageeditarea.h"
#include "mainwidget.h"
#include "soundrecorder.h"

MessageEditArea::MessageEditArea(QWidget* owner) : owner(owner)
{
    this->setFixedHeight(150);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    this->setStyleSheet("QWidget{background-color:rgb(245,245,245);}");

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(30,10,30,10);
    layout->setSpacing(0);
    this->setLayout(layout);

    //创建工具按钮容器
    QWidget* toolsContainer = new QWidget();
    toolsContainer->setFixedHeight(40);
    layout->addWidget(toolsContainer,0,Qt::AlignTop);

    //创建水平布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setContentsMargins(0,0,0,0);
    hlayout->setSpacing(10);
    hlayout->setAlignment(Qt::AlignLeft);
    toolsContainer->setLayout(hlayout);

    //向水平布局管理器中添加按钮
    sendFileBtn = new QPushButton();
    sendImageBtn = new QPushButton();
    sendSoundBtn = new QPushButton();
    showHistoryBtn = new QPushButton();

    QString buttonStyle = "QPushButton { background-color: rgb(245, 245, 245);border: none; } QPushButton:pressed { background-color: rgb(255, 255, 255);}";
    QSize buttonSize(20,20);


    sendFileBtn->setStyleSheet(buttonStyle);
    sendFileBtn->setFixedSize(buttonSize);
    sendFileBtn->setIconSize(buttonSize);
    sendFileBtn->setIcon(QIcon(":/image/file.png"));
    sendFileBtn->setCursor(Qt::PointingHandCursor);

    sendImageBtn->setStyleSheet(buttonStyle);
    sendImageBtn->setFixedSize(buttonSize);
    sendImageBtn->setIconSize(buttonSize);
    sendImageBtn->setIcon(QIcon(":/image/image.png"));
    sendImageBtn->setCursor(Qt::PointingHandCursor);

    sendSoundBtn->setStyleSheet(buttonStyle);
    sendSoundBtn->setFixedSize(buttonSize);
    sendSoundBtn->setIconSize(buttonSize);
    sendSoundBtn->setIcon(QIcon(":/image/sound.png"));
    sendSoundBtn->setCursor(Qt::PointingHandCursor);

    showHistoryBtn->setStyleSheet(buttonStyle);
    showHistoryBtn->setFixedSize(buttonSize);
    showHistoryBtn->setIconSize(buttonSize);
    showHistoryBtn->setIcon(QIcon(":/image/history.png"));
    showHistoryBtn->setCursor(Qt::PointingHandCursor);

    hlayout->addWidget(sendFileBtn);
    hlayout->addWidget(sendImageBtn);
    hlayout->addWidget(sendSoundBtn);
    hlayout->addWidget(showHistoryBtn);


    //创建文本输入框
    textEdit = new QPlainTextEdit();
    textEdit->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    textEdit->setStyleSheet("QPlainTextEdit{background-color:rgb(245,245,245); border:none;}");
    layout->addWidget(textEdit);

    //创建语音录制时提示
    tipLabel = new QLabel();
    tipLabel->setText("正在录音中...");
    tipLabel->setAlignment(Qt::AlignCenter);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    layout->addWidget(tipLabel);
    tipLabel->hide();

    //创建发送按钮
    sendBtn = new QPushButton();
    sendBtn->setFixedSize(100,35);
    sendBtn->setText("发送");
    sendBtn->setStyleSheet("QPushButton{background-color:rgb(233, 233, 233); border:none; border-radius:5px; font-size: 10px;} QPushButton:hover{background-color:rgb(210, 210, 210);}");
    layout->addWidget(sendBtn,0,Qt::AlignRight | Qt::AlignBottom);

    initSignalsAndSlots();
}

void MessageEditArea::initSignalsAndSlots()
{
    DataCenter* dataCenter = DataCenter::getInstance();

    ////////////////////////////////////////////////////////////
    /// 关联发送消息按钮逻辑
    ////////////////////////////////////////////////////////////
    /// 消息发送逻辑
    connect(sendBtn,&QPushButton::clicked,this,&MessageEditArea::sendTextMessage);

    /// 消息到来后的接受逻辑
    connect(dataCenter,&DataCenter::sendMessageDone,this,&MessageEditArea::addSelfMessage,Qt::UniqueConnection);

    /// 关联发送图片按钮逻辑
    connect(sendImageBtn,&QPushButton::clicked,this,&MessageEditArea::clickSendImageBtn);

    /// 关联发送文件按钮逻辑
    connect(sendFileBtn,&QPushButton::clicked,this,&MessageEditArea::clickSendFileBtn);

    /// 关联发送语音按钮逻辑
    SoundRecorder* soundRecorder = SoundRecorder::getInstance();
    connect(sendSoundBtn,&QPushButton::pressed,this,&MessageEditArea::soundRecordPressed);
    connect(sendSoundBtn,&QPushButton::released,this,&MessageEditArea::soundRecordReleased);
    connect(soundRecorder,&SoundRecorder::soundRecordDone,this,&MessageEditArea::sendSound);

    //////////////////////////////////////////////////////////////
    /// 关联历史按钮逻辑
    connect(showHistoryBtn,&QPushButton::clicked,this,[=](){
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        if(dataCenter->getCurrentChatSessionId().isEmpty())
        {
            Toast::showMessage("你当前未选中任何会话, 无法查看历史消息!");
            return;
        }
        HistoryMessageWidget* dialog = new HistoryMessageWidget(this);
        dialog->exec();
    });




}

void MessageEditArea::sendTextMessage()
{
    //1. 如果当前没有选中会话,则什么都不做
    DataCenter* dataCenter = DataCenter::getInstance();

    if(dataCenter->getCurrentChatSessionId().isEmpty())
    {
        LOG() << "当前未选中会话, 不发送任何消息!";
        Toast::showMessage("当前未选中会话, 不发送任何消息!");
        return;
    }

    //2. 如果选中会话, 但未输入数据, 同样什么都不做
    QString content = textEdit->toPlainText().trimmed();

    if(content.isEmpty())
    {
        LOG() << "当前未输入有效数据, 不发送任何消息!";
        Toast::showMessage("当前未输入有效数据, 不发送任何消息!");
        return;
    }

    //3. 已经获取有效数据, 准备发送, 发送前清空输入框已有内容
    textEdit->setPlainText("");

    //4. 通过网络发送有效数据
    dataCenter->sendTextMessageAsync(dataCenter->getCurrentChatSessionId(),content.toUtf8());
}

void MessageEditArea::addSelfMessage(const QByteArray &content, MessageType type, const QString &extraInfo)
{
    DataCenter* dataCenter = DataCenter::getInstance();

    //获取当前选中的会话id
    QString curChatSessionId = dataCenter->getCurrentChatSessionId();
    //构造消息对象

    //添加消息对象到dataCenter中
    Message message = Message::makeMessage(*dataCenter->getMyself(),type,content,curChatSessionId,extraInfo);
    dataCenter->addMessage(message);

    //添加新消息对象的显示
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->getMessageShowArea()->addMessage(false, message);

    //设置滚动条为末尾
    mainWidget->getMessageShowArea()->srcollToEnd();

    emit dataCenter->updateLastMessage(curChatSessionId);
}

void MessageEditArea::addOtherMessage(const Message &message)
{
    //添加新消息对象的显示
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->getMessageShowArea()->addMessage(true, message);

    //设置滚动条为末尾
    mainWidget->getMessageShowArea()->srcollToEnd();

    //提示用户收到新消息
    Toast::showMessage("收到新消息");
}

void MessageEditArea::clickSendImageBtn()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    if(dataCenter->getCurrentChatSessionId() == "")
    {
        Toast::showMessage("当前没有选中会话!");
        return;
    }

    QString filter = "Image files (*.png *.jpeg *.jpg *.bmp)";

    QString filePath = QFileDialog::getOpenFileName(this,"选择图片文件",QDir::homePath(),filter);

    if(filePath.isEmpty())
    {
        LOG() << "用户未选择图片文件!";
        return;
    }

    dataCenter->sendImageMessageAsync(dataCenter->getCurrentChatSessionId(),loadFileToByteArray(filePath));

}

void MessageEditArea::clickSendFileBtn()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    if(dataCenter->getCurrentChatSessionId()== "")
    {
        Toast::showMessage("当前没有选中会话");
        return;
    }

    QString filePath = QFileDialog::getOpenFileName(this,"选择文件",QDir::homePath(),"files (*)");

    if(filePath.isEmpty())
    {
        LOG() << "用户取消了文件选择";
        return;
    }

    //获取⽂件名
    QFileInfo fileInfo(filePath);
    const QString& fileName = fileInfo.fileName();

    dataCenter->sendFileMessageAsync(dataCenter->getCurrentChatSessionId(),loadFileToByteArray(filePath),fileName);
}

void MessageEditArea::soundRecordPressed()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    if(dataCenter->getCurrentChatSessionId()=="")
    {
        Toast::showMessage("请选择会话!");
        return;
    }

    sendSoundBtn->setIcon(QIcon(":/image/sound_active.png"));
    SoundRecorder* soundRecorder = SoundRecorder::getInstance();
    soundRecorder->startRecord();

    textEdit->hide();
    tipLabel->show();

}

void MessageEditArea::soundRecordReleased()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    if(dataCenter->getCurrentChatSessionId()=="")
    {
        Toast::showMessage("请选择会话!");
        return;
    }

    sendSoundBtn->setIcon(QIcon(":/image/sound.png"));
    SoundRecorder* soundRecorder = SoundRecorder::getInstance();
    soundRecorder->stopRecord();

    textEdit->show();
    tipLabel->hide();
}

void MessageEditArea::sendSound(const QString &path)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    QByteArray content = loadFileToByteArray(path);

    dataCenter->sendSpeechMessageAsync(dataCenter->getCurrentChatSessionId(),content);
}
















